using Microsoft.AspNetCore.Mvc;
using net_work.Common.Request;
using net_work.Data.DTO.System;
using net_work.Data.Entity.System;
using net_work.IRepository.System;
using net_work.IService.System;

namespace net_work.Service.System;

public class FileService(IFileRepository fileRepository) : IFileService
{
    public async Task<int> UploadFile(IFormFile file, FileUseAddRequest fileUseAddRequest)
    {
        // 确定根存储目录
        var rootDirectory = Path.Combine(Directory.GetCurrentDirectory(), "FileStore");

        // 创建业务编码对应的子文件夹
        var directoryPath = Path.Combine(rootDirectory, fileUseAddRequest.BusinessCode.ToString());
        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        // 生成文件路径
        var filePath = Path.Combine(directoryPath, file.FileName);

        // 保存文件到磁盘
        await using var fileStream = new FileStream(filePath, FileMode.Create);
        await file.CopyToAsync(fileStream);

        var myFileAddRequest = new MyFileAddRequest()
        {
            FilePath = filePath,
            FileName = file.FileName,
            FileType = file.ContentType
        };

        var pagedResult = await fileRepository.GetPagedAsync(new PagedRequest(1, PageSizeEnum.Unlimited,
            [new FilterCondition("FilePath", FilterOperator.Equals, filePath)]));
        if (pagedResult.TotalRecords <= 0)
        {
            return await fileRepository.UploadFile(fileUseAddRequest, myFileAddRequest);
        }

        return 1;
    }

    public async Task<int> DeleteFiles(List<long> ids)
    {
        return await fileRepository.DeleteByIdsAsync(ids) ? 1 : -1;
    }

    public Task<List<MyFile>> GetFileList(FileUseAddRequest fileUseAddRequest)
    {
        return fileRepository.GetFileList(fileUseAddRequest);
    }

    public async Task<FileStreamResult?> DownloadStream(long myFileId)
    {
        var file = await fileRepository.GetByIdAsync(myFileId);
        if (file == null || string.IsNullOrEmpty(file.FilePath))
        {
            throw new FileNotFoundException("File not found");
        }

        if (!File.Exists(file.FilePath))
        {
            throw new FileNotFoundException("File not found on disk");
        }

        // 创建文件流
        var stream = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read);
        return new FileStreamResult(stream, file.FileType)
        {
            FileDownloadName = file.FileName
        };
    }
}